package cn.yujiago.miaosha.service.impl;

import cn.yujiago.miaosha.dto.GoodsDTO;
import cn.yujiago.miaosha.entity.MiaoshaOrder;
import cn.yujiago.miaosha.entity.Order;
import cn.yujiago.miaosha.mapper.OrderMapper;
import cn.yujiago.miaosha.redis.OrderKey;
import cn.yujiago.miaosha.redis.RedisService;
import cn.yujiago.miaosha.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RedisService redisService;

    @Override
    public Order getOrderById(Long orderId) {
        return orderMapper.selectOrderById(orderId);
    }

    @Transactional
    @Override
    public Order createOrder(Long userId, GoodsDTO goods) {
        Order order = new Order();
        order.setCreateDate(new Date());
        order.setDeliveryAddrId(0L);
        order.setGoodsCount(1);
        order.setGoodsId(goods.getId());
        order.setGoodsName(goods.getGoodsName());
        order.setGoodsPrice(goods.getMiaoshaPrice());
        order.setOrderChannel(1);
        order.setStatus(0);
        order.setUserId(userId);
        // 生成订单
        orderMapper.insert(order);
        MiaoshaOrder miaoshaOrder = new MiaoshaOrder();
        miaoshaOrder.setGoodsId(goods.getId());
        miaoshaOrder.setOrderId(order.getId());
        miaoshaOrder.setUserId(userId);
        // 生成秒杀订单
        orderMapper.insertMiaoshaOrder(miaoshaOrder);
        // 将秒杀订单写入缓存
        redisService.set(OrderKey.getMiaoshaOrderByUidGid, ""+userId+"_"+goods.getId(), miaoshaOrder);

        return order;
    }

    @Override
    public MiaoshaOrder getMiaoshaOrderByUserIdGoodsId(Long userId, Long goodsId) {
        return redisService.get(OrderKey.getMiaoshaOrderByUidGid, ""+userId+"_"+goodsId, MiaoshaOrder.class);
    }
}
